package com.mayikt.strategy.impl;

import com.mayikt.entity.UnionLoginDO;
import com.mayikt.entity.UserDO;
import com.mayikt.http.HttpClientUtils;
import com.mayikt.mapper.UserMapper;
import com.mayikt.strategy.UnionLoginStrategy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Name QQUnionLoginStrategy
 * @Author 枫火
 * @Date 2021/5/28 10:33
 * @Description
 **/
@Component
public class QQUnionLoginStrategy implements UnionLoginStrategy {

    @Value("${mayikt.login.qq.accesstoken}")
    private String qqAccessTokenAddress;
    @Value("${mayikt.login.qq.openid}")
    private String qqOpenIdAddress;
    @Autowired
    private UserMapper userMapper;

    @Override
    public String unionLoginCallback(HttpServletRequest request, UnionLoginDO unionLoginDo) {
        String code = request.getParameter("code");
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        // 根据授权码获取accessToken
        String tokenAddress = qqAccessTokenAddress.replace("{client_id}", unionLoginDo.getAppId()).replace("{client_secret}", unionLoginDo.getAppKey()).
                replace("{code}", code).replace("{redirect_uri}", unionLoginDo.getRedirectUri());
        String resultAccessToken = HttpClientUtils.httpGetResultString(tokenAddress);
        boolean contains = resultAccessToken.contains("access_token=");
        if (!contains) {
            return null;
        }
        String[] split = resultAccessToken.split("=");
        String accessToken = split[1];
        if (StringUtils.isEmpty(accessToken)) {
            return null;
        }
        // 2.根据accessToken获取用户的openId
        String resultQQOpenId = HttpClientUtils.httpGetResultString(qqOpenIdAddress + accessToken);
        if (StringUtils.isEmpty(resultQQOpenId)) {
            return null;
        }
        boolean openid = resultQQOpenId.contains("openid");
        if (!openid) {
            return null;
        }
        String array[] = resultQQOpenId.replace("callback( {", "").
                replace("} );", "").split(":");
        String openId = array[2].replace("\n","").replace("\"", "");
        return openId;
    }

    @Override
    public UserDO getDbOpenId(String openId) {
        return userMapper.selectByQQOpenId(openId);
    }

    @Override
    public int updateUseOpenId(Long userId, String openId) {
        return userMapper.updateUserOpenId(userId,openId);
    }
}
